{% load i18n grp_tags static admin_urls %}

<!-- group -->
<div class="inline-group grp-group grp-tabular{% if inline_admin_formset.opts.classes %} {{ inline_admin_formset.opts.classes|join:" " }}{% endif %}"
    id="{{ inline_admin_formset.formset.prefix }}-group" >
    {% block tabular_content %}
        <h2 class="grp-collapse-handler">{% if inline_admin_formset.opts.title %}{{ inline_admin_formset.opts.title }}{% else %}{{ inline_admin_formset.opts.verbose_name_plural|capfirst }}{% endif %}</h2>
        <ul class="grp-tools">
            <li><a href="javascript://" class="grp-icon grp-add-handler" title="{% trans 'Add Another' %}"> </a></li>
        </ul>
        {{ inline_admin_formset.formset.management_form }}
        {{ inline_admin_formset.formset.non_form_errors }}
        <!-- container -->
        <div class="tabular inline-related grp-module grp-table">
            <div class="module grp-module grp-thead">
                <div class="grp-tr">
                    {% for field in inline_admin_formset.fields %}
                        {% if not field.widget.is_hidden %}
                            <div class="grp-th {{ field.label|lower|slugify }}{% if field.required %} required{% endif %}">
                                {{ field.label|capfirst }}
                                {% if field.help_text %}&nbsp;<img src="{% static "admin/img/icon-unknown.svg" %}" class="grp-help-tooltip" width="12" height="12" alt="({{ field.help_text|striptags }})" title="{{ field.help_text|striptags }}" />{% endif %}
                            </div>
                        {% endif %}
                    {% endfor %}
                    {% if inline_admin_formset.formset.can_delete %}<div class="grp-th">&nbsp;</div>{% endif %}
                </div>
            </div>
            {% with inline_admin_formset.opts.sortable_field_name|default:"" as sortable_field_name %}
            {% for inline_admin_form in inline_admin_formset|formsetsort:sortable_field_name %}
                <!-- element -->
                <div class="form-row grp-module grp-tbody{% if inline_admin_form.original or inline_admin_form.show_url %} has_original{% endif %}{% if forloop.last and inline_admin_formset.has_add_permission %} grp-empty-form{% endif %}"
                    id="{{ inline_admin_formset.formset.prefix }}{% if forloop.last and inline_admin_formset.has_add_permission %}-empty{% else %}{{ forloop.counter0 }}{% endif %}">
                    {% if inline_admin_form.form.non_field_errors %}
                        {{ inline_admin_form.form.non_field_errors }}
                    {% endif %}
                    <h3 style="display: none;"><b>{{ inline_admin_formset.opts.verbose_name }} #{{ forloop.counter }}</b>&nbsp;&nbsp;{% if inline_admin_form.original %} {{ inline_admin_form.original }}{% endif %}</h3>
                    {% spaceless %}
                    {% for fieldset in inline_admin_form %}
                        {% for line in fieldset %}
                            {% for field in line %}
                                {% if field.field.is_hidden %}
                                    <div style="display: none;">
                                        {% if field.is_readonly %}
                                            {{ field.contents }}
                                        {% else %}
                                            {{ field.field }}
                                        {% endif %}
                                    </div>
                                {% endif %}
                            {% endfor %}
                        {% endfor %}
                    {% endfor %}
                    {% endspaceless %}
                    <div class="grp-tr">
                        {% for fieldset in inline_admin_form %}
                            {% for line in fieldset %}
                                {% for field in line %}
                                    {% if not field.field.is_hidden %}
                                        <div class="grp-td {{ field.field.name }} {% if field.field.errors %} grp-errors{% endif %}">
                                            {% if field.is_readonly %}
                                                <div class="grp-readonly">{{ field.contents }}</div>
                                            {% else %}
                                                {{ field.field }}
                                                {{ field.field.errors.as_ul }}
                                            {% endif %}
                                            {% comment %}{% if field.field.help_text %}<p class="grp-help">{{ field.field.help_text }}</p>{% endif %}{% endcomment %}
                                        </div>
                                    {% endif %}
                                {% endfor %}
                            {% endfor %}
                        {% endfor %}
                        <div class="grp-td grp-tools-container">
                            {% spaceless %}
                            <ul class="grp-tools">
                                {% if inline_admin_form.original %}
                                    {% if inline_admin_form.model_admin.show_change_link and inline_admin_form.model_admin.has_registered_model %}
                                        <li><a href="{% url inline_admin_form.model_admin.opts|admin_urlname:'change' inline_admin_form.original.pk|admin_urlquote %}" class="grp-icon grp-edit-link" title="{% trans 'Change' %}"></a></li>
                                    {% endif %}
                                {% endif %}
                                {% if inline_admin_form.show_url %}<li><a href="{{ inline_admin_form.absolute_url }}" class="grp-icon grp-viewsite-link" title="{% trans 'View on Site' %}" target="_blank"></a></li>{% endif %}
                                {% if inline_admin_formset.opts.sortable_field_name %}
                                    <li><a href="javascript://" class="grp-icon grp-drag-handler" title="{% trans 'Move Item' %}"></a></li>
                                {% endif %}
                                {% if inline_admin_form.original %}
                                    {% if inline_admin_formset.formset.can_delete %}
                                        <li class="grp-delete-handler-container">{{ inline_admin_form.deletion_field.field }}<a href="javascript://" class="grp-icon grp-delete-handler" title="{% trans 'Delete Item' %}"></a></li>
                                    {% else %}
                                        <li><span class="grp-icon">&nbsp;</span></li>
                                    {% endif %}
                                {% else %}
                                    <li><a href="javascript://" class="grp-icon grp-remove-handler" title="{% trans 'Delete Item' %}"></a></li>
                                {% endif %}
                            </ul>
                            {% endspaceless %}
                        </div>
                        {{ inline_admin_form.fk_field.field }}
                        {% if inline_admin_form.has_auto_field or inline_admin_form.needs_explicit_pk_field %}{{ inline_admin_form.pk_field.field }}{% endif %}
                    </div>
                </div>
            {% endfor %}
            {% endwith %}
        </div>
        <div class="grp-module grp-transparent">
            <div class="grp-row">
                <a href="javascript://" class="grp-add-handler"><strong>{% blocktrans with inline_admin_formset.opts.verbose_name as verbose_name %}Add another {{ verbose_name }}{% endblocktrans %}</strong></a>
                <ul class="grp-tools">
                    <li><a href="javascript://" class="grp-icon grp-add-handler" title="{% trans 'Add Item' %}"></a></li>
                </ul>
            </div>
        </div>
    {% endblock %}
</div>

<script type="text/javascript">
(function($) {
    $(document).ready(function($) {

        var prefix = "{{ inline_admin_formset.formset.prefix }}";
        var related_lookup_fields_fk = {% get_related_lookup_fields_fk inline_admin_formset.opts %};
        var related_lookup_fields_m2m = {% get_related_lookup_fields_m2m inline_admin_formset.opts %};
        var related_lookup_fields_generic = {% get_related_lookup_fields_generic inline_admin_formset.opts %};
        var autocomplete_fields_fk = {% get_autocomplete_lookup_fields_fk inline_admin_formset.opts %};
        var autocomplete_fields_m2m = {% get_autocomplete_lookup_fields_m2m inline_admin_formset.opts %};
        var autocomplete_fields_generic = {% get_autocomplete_lookup_fields_generic inline_admin_formset.opts %};
        $.each(related_lookup_fields_fk, function() {
            $("#{{ inline_admin_formset.formset.prefix }}-group > div.grp-table > div:not(.grp-empty-form)")
            .find("input[name^='" + prefix + "'][name$='-" + this + "']")
            .grp_related_fk({lookup_url:"{% url 'grp_related_lookup' %}"});
        });
        $.each(related_lookup_fields_m2m, function() {
            $("#{{ inline_admin_formset.formset.prefix }}-group > div.grp-table > div:not(.grp-empty-form)")
            .find("input[name^='" + prefix + "'][name$='-" + this + "']")
            .grp_related_m2m({lookup_url:"{% url 'grp_m2m_lookup' %}"});
        });
        $.each(related_lookup_fields_generic, function() {
            var content_type = this[0],
                object_id = this[1];
            $("#{{ inline_admin_formset.formset.prefix }}-group > div.grp-table > div:not(.grp-empty-form)")
            .find("input[name^='" + prefix + "'][name$='-" + this[1] + "']")
            .each(function() {
                var i = $(this).attr("id").match(/(?:-\d+)?(-\d+-)/);
                if (i) {
                    var ct_id = "#id_" + prefix + i[1] + content_type,
                        obj_id = "#id_" + prefix + i[1] + object_id;
                    $(this).grp_related_generic({content_type:ct_id, object_id:obj_id, lookup_url:"{% url 'grp_related_lookup' %}"});
                }
            });
        });
        $.each(autocomplete_fields_fk, function() {
            $("#{{ inline_admin_formset.formset.prefix }}-group > div.grp-table > div:not(.grp-empty-form)")
            .find("input[name^='" + prefix + "'][name$='-" + this + "']")
            .each(function() {
                $(this).grp_autocomplete_fk({
                    lookup_url:"{% url 'grp_related_lookup' %}",
                    autocomplete_lookup_url:"{% url 'grp_autocomplete_lookup' %}"
                });
            });
        });
        $.each(autocomplete_fields_m2m, function() {
            $("#{{ inline_admin_formset.formset.prefix }}-group > div.grp-table > div:not(.grp-empty-form)")
            .find("input[name^='" + prefix + "'][name$='-" + this + "']")
            .each(function() {
                $(this).grp_autocomplete_m2m({
                    lookup_url:"{% url 'grp_m2m_lookup' %}",
                    autocomplete_lookup_url:"{% url 'grp_autocomplete_lookup' %}"
                });
            });
        });
        $.each(autocomplete_fields_generic, function() {
            var content_type = this[0],
                object_id = this[1];
            $("#{{ inline_admin_formset.formset.prefix }}-group > div.grp-table > div:not(.grp-empty-form)")
            .find("input[name^='" + prefix + "'][name$='-" + this[1] + "']")
            .each(function() {
                var i = $(this).attr("id").match(/(?:-\d+)?(-\d+-)/);
                if (i) {
                    var ct_id = "#id_" + prefix + i[1] + content_type,
                        obj_id = "#id_" + prefix + i[1] + object_id;
                    $(this).grp_autocomplete_generic({
                        content_type:ct_id,
                        object_id:obj_id,
                        lookup_url:"{% url 'grp_related_lookup' %}",
                        autocomplete_lookup_url:"{% url 'grp_autocomplete_lookup' %}"
                    });
                }
            });
        });

        $("#{{ inline_admin_formset.formset.prefix }}-group").grp_inline({
            {% block grp_inline_options %}
            prefix: "{{ inline_admin_formset.formset.prefix }}",
            onBeforeAdded: function(inline) {},
            onAfterAdded: function(form) {
                grappelli.reinitDateTimeFields(form);
                grappelli.updateSelectFilter(form);
                $.each(related_lookup_fields_fk, function() {
                    form.find("input[name^='" + prefix + "'][name$='-" + this + "']")
                    .grp_related_fk({lookup_url:"{% url 'grp_related_lookup' %}"});
                });
                $.each(related_lookup_fields_m2m, function() {
                    form.find("input[name^='" + prefix + "'][name$='-" + this + "']")
                    .grp_related_m2m({lookup_url:"{% url 'grp_m2m_lookup' %}"});
                });
                $.each(related_lookup_fields_generic, function() {
                    var content_type = this[0],
                        object_id = this[1];
                    form.find("input[name^='" + prefix + "'][name$='-" + this[1] + "']")
                    .each(function() {
                        var i = $(this).attr("id").match(/(?:-\d+)?(-\d+-)/);
                        if (i) {
                            var ct_id = "#id_" + prefix + i[1] + content_type,
                                obj_id = "#id_" + prefix + i[1] + object_id;
                            $(this).grp_related_generic({content_type:ct_id, object_id:obj_id, lookup_url:"{% url 'grp_related_lookup' %}"});
                        }
                    });
                });
                $.each(autocomplete_fields_fk, function() {
                    form.find("input[name^='" + prefix + "'][name$='-" + this + "']")
                    .each(function() {
                        $(this).grp_autocomplete_fk({
                            lookup_url:"{% url 'grp_related_lookup' %}",
                            autocomplete_lookup_url:"{% url 'grp_autocomplete_lookup' %}"
                        });
                    });
                });
                $.each(autocomplete_fields_m2m, function() {
                    form.find("input[name^='" + prefix + "'][name$='-" + this + "']")
                    .each(function() {
                        $(this).grp_autocomplete_m2m({
                            lookup_url:"{% url 'grp_m2m_lookup' %}",
                            autocomplete_lookup_url:"{% url 'grp_autocomplete_lookup' %}"
                        });
                    });
                });
                $.each(autocomplete_fields_generic, function() {
                    var content_type = this[0],
                        object_id = this[1];
                    form.find("input[name^='" + prefix + "'][name$='-" + this[1] + "']")
                    .each(function() {
                        var i = $(this).attr("id").match(/(?:-\d+)?(-\d+-)/);
                        if (i) {
                            var ct_id = "#id_" + prefix + i[1] + content_type,
                                obj_id = "#id_" + prefix + i[1] + object_id;
                            $(this).grp_autocomplete_generic({
                                content_type:ct_id,
                                object_id:obj_id,
                                lookup_url:"{% url 'grp_related_lookup' %}",
                                autocomplete_lookup_url:"{% url 'grp_autocomplete_lookup' %}"
                            });
                        }
                    });
                });
            }
            {% endblock %}
        });

        {% if inline_admin_formset.opts.sortable_field_name %}
        $("#{{ inline_admin_formset.formset.prefix }}-group > div.grp-table").sortable({
            handle: "a.grp-drag-handler",
            items: "div.grp-dynamic-form",
            axis: "y",
            appendTo: 'parent',
            forceHelperSize: true,
            placeholder: 'grp-module ui-sortable-placeholder',
            forcePlaceholderSize: true,
            containment: '#{{ inline_admin_formset.formset.prefix }}-group > div.grp-table',
            tolerance: 'pointer',
            start: function(evt, ui) {
                var template = "<div class='grp-tr'>",
                    len = ui.item.find("div.grp-tr").children("div.grp-td").length;
                for (var i = 0; i < len; i++) {
                    template += "<div class='grp-td' style='height:" + (ui.item.outerHeight() + 12 ) + "px'>&nbsp;</div>";
                }
                template += "</div>";
                ui.placeholder.addClass("grp-tbody grp-module").append(template);
            },
            stop: function(evt, ui) {
                var lastScrollTop = $(window).scrollTop();
                // Toggle div.table twice to remove webkits border-spacing bug
                $("#{{ inline_admin_formset.formset.prefix }}-group > div.grp-table").toggle().toggle();
                $(window).scrollTop(lastScrollTop);
            }
        });
        /*
        Enables changing the sort order manually on sort field change
        - Top entry is 0
        - Last entry is n-1. Or any number that equals or is greater than n.
        - Sortables without a value (extra forms) are not respected. If they are at the end, they stay there.
        - Non-Number and negative numbers are being ignored.
        - It does not cleans up the order field values on change (just like dragging does not do that).
        */
        $.fn.grp_reverse_list = [].reverse;
        $("#{{ inline_admin_formset.formset.prefix }}-group")
            .find("div.grp-td.{{ inline_admin_formset.opts.sortable_field_name }} :input")
            .each(function(i, item) {
                $(item).on('change', function(event) {
                    var desired_index = $(event.target).val() * 1;
                    if(!isNaN(desired_index) && desired_index >= 0) {
                        var $row = $(event.target).parents('div.grp-tbody.grp-dynamic-form');
                        var $table = $row.parents('div.grp-module.grp-table.ui-sortable');
                        $row.detach();
                        var $row_desired = $table.children('div.grp-tbody.grp-dynamic-form').get(desired_index);
                        if($row_desired) {
                            $row.insertBefore($row_desired);
                            $row.find('div.grp-td').effect('highlight', {color:"#ffffcc"}, 2000);
                        } else {
                            // FIXME: this appends the new row to the very end of the table.
                            // instead, it should be added after the last row with values.
                            $table.append($row);
                            $row.find('div.grp-td').effect('highlight', {color:"#ffffcc"}, 2000);
                        }
                    }
                });
            });
        $("#{{ opts.model_name }}_form").on("submit", function(){
            var sortable_field_name = "{{ inline_admin_formset.opts.sortable_field_name }}",
                sortable_excludes = {% get_sortable_excludes inline_admin_formset.opts %},
                i = 0;
            $("#{{ inline_admin_formset.formset.prefix }}-group").find("div.grp-tbody.grp-dynamic-form").each(function(){
                var fields = $(this).find("div.grp-td :input[type!=radio][type!=checkbox],input:checked,input[type=file]"),
                    submit_values = false,
                    has_value;
                $(fields).each(function() {
                    // position is being updated if
                    // a) the field has a value
                    // b) if the field is not exluded with sortable_excludes (e.g. with default values)
                    has_value = $(this).val() || ($(this).attr('type') == 'file' && $(this).siblings('a').length);
                    if (has_value && $(this).attr("name") && $.inArray($(this).attr("name").split("-").pop(), sortable_excludes) == -1) {
                        submit_values = true;
                    }
                });
                if (submit_values) {
                    $(this).find("input[name$='-"+sortable_field_name+"']").val(i);
                    i++;
                }
            });
        });
        {% endif %}

    });
})(grp.jQuery);
</script>
